<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/admin/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/plugin/bootstrap-multitabs/multitabs.min.css"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/plugin/bootstrap-select/bootstrap-select.css"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/plugin/jquery-confirm/jquery-confirm.min.css"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/admin/css/style.min.css"/>
    <link rel="stylesheet" type="text/css" href="/assets/static/plugin/bootstrap-fileinput/css/fileinput.min.css"/>
</head>

<body>
<div class="container-fluid p-t-15">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-toolbar d-flex flex-column flex-md-row justify-content-between">
                    <div class="toolbar-btn-action">
                        <a class="btn btn-primary m-r-5" href="/admin/site/add"><i class="mdi mdi-plus"></i> 新增</a>
                        <button class="btn btn-success m-r-5" id="exportBtn"><i class="mdi mdi-download"></i> 导出</button>
                    </div>
                    <div class="d-flex align-items-center">
                        <div class="form-group m-b-0">
                            <input class="form-control" type="text" id="search-keyword" name="search-keyword" placeholder="请输入网址标题..."/>
                        </div>
                        <div class="form-group m-b-0 m-l-10">
                            <select class="form-control selectpicker" id="category-filter" data-live-search="true">
                                <option value="">全部分类</option>
                                <!-- 分类选项将通过 JavaScript 动态加载 -->
                            </select>
                        </div>
                        <div class="form-group m-b-0 m-l-10">
                            <button class="btn btn-outline-success btn-search" type="submit">搜索</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="alert alert-info" role="alert">注📢: 勾选"拉取失败时仅保存网址"功能对应行背景色高亮, 记得点击编辑修改呦!</div>
                    <div class="table-responsive">
                        <table class="table table-bordered" id="siteTable">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>Logo</th>
                                <th>名称简介</th>
                                <th>链接</th>
                                <th>分类</th>
                                <th>创建日期</th>
                                <th>更新日期</th>
                                <th style="text-align: center; ">状态</th>
                                <th style="text-align: center;">排序</th> <!-- 新增排序列 -->
                                <th style="text-align: center; ">操作</th>
                            </tr>
                            </thead>
                            <tbody class="tbody"></tbody>
                        </table>
                    </div>
                    <ul class="pagination" id="paginationDiv"></ul>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="/assets/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/assets/static/admin/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="/assets/static/plugin/bootstrap-maxlength/bootstrap-maxlength.min.js"></script>
<script type="text/javascript" src="/assets/static/plugin/jquery-confirm/jquery-confirm.min.js"></script>
<script type="text/javascript" src="/assets/static/plugin/bootstrap-select/bootstrap-select.min.js"></script>
<script type="text/javascript" src="/assets/static/plugin/bootstrap-select/i18n/defaults-zh_CN.min.js"></script>
<script type="text/javascript" src="/assets/static/plugin/bootstrap-multitabs/multitabs.min.js"></script>
<script type="text/javascript" src="/assets/static/admin/js/httpclient.js"></script>
<script type="text/javascript" src="/assets/static/admin/js/jquery.pagination.js"></script>
<script src="/assets/static/plugin/bootstrap-fileinput/js/fileinput.min.js"></script>
<script src="/assets/static/plugin/bootstrap-fileinput/js/locales/zh.min.js"></script>
<script type="text/javascript" src="/assets/static/admin/js/utils.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        // 加载分类选项
        loadCategories();
        // 监听分类选择器的变化
        $(document).on('change', '#category-filter', function () {
            const categoryId = $(this).val(); // 获取选中的分类ID
            const searchKeyword = $("#search-keyword").val(); // 获取搜索关键字
            getPageListData(1, 10, searchKeyword, categoryId); // 重新加载数据
        });
        // 加载列表页数据
        getPageListData();

        // 加载分类选项的函数
        function loadCategories() {
            AjaxForm(
                "GET",
                "/api/admin/category",
                {},
                function () {
                },
                function (data) {
                    const categoryFilter = $("#category-filter");
                    categoryFilter.empty();
                    categoryFilter.append('<option value="">全部分类</option>');
                    $.each(data.list, function (index, category) {
                        categoryFilter.append('<option value="' + category.id + '">' + category.name + '</option>');
                    });
                    categoryFilter.selectpicker('refresh');
                },
                function (response) {
                    AjaxError(response);
                }
            );
        }

        // 获取分页数据的函数
        function getPageListData(page = 1, page_size = 10, search = null, category_id = null, url = "/api/admin/site") {
            if (parseInt(page) < 1) {
                page = 1;
            }
            if (parseInt(page_size) < 1) {
                page_size = 10;
            }
            AjaxForm(
                "GET",
                url,
                {page: page, page_size: page_size, search: search, category_id: category_id},
                function () {
                },
                function (data) {
                    if (data.list.length > 0) {
                        var totalNum = data.pagination.total; // 总条数
                        var pageNum = Math.ceil(totalNum / data.pagination.per_page_count); // 分页的总页数
                        $("#paginationDiv").pagination({
                            current: data.pagination.current_page,
                            pageCount: pageNum,
                            coping: true,
                            homePage: '首页',
                            endPage: '末页',
                            mode: 'fixed',
                            prevContent: '上一页',
                            nextContent: '下一页',
                            activeCls: 'pageActive',
                            prevCls: 'pagePrev',
                            nextCls: 'pageNext',
                            callback: function (api) {
                                $(".tbody").html("");
                                getPageListData(api.getCurrent(), 10, $("#search-keyword").val(), $("#category-filter").val());
                            }
                        });
                        $(".tbody").html("");
                        $.each(data.list, function (index, value) {
                            let showUsedBadge;
                            let optionUsedName;
                            if (value.is_used) {
                                optionUsedName = '禁用';
                                showUsedBadge = '<span class="badge badge-success">启用</span></td>'
                            } else {
                                optionUsedName = '启用';
                                showUsedBadge = '<span class="badge badge-danger">禁用</span></td>'
                            }

                            let trHtml = '<tr>';
                            if (value.url === value.title) { // 如果url和title相同，则显示警告样式
                                trHtml = '<tr class="table-warning">'
                            }

                            const tr = trHtml +
                                '<td>' + value.id + '</td>' +
                                '<td><img class="lozad img-circle" width="30" src="data:image/png;base64,' + value.icon + '" data-loaded="true"></td>' +
                                '<td>' + value.title + '</td>' +
                                '<td><a href="' + value.url + '" target="_blank">' + value.url + '</a></td>' +
                                '<td>' + value.category + '</td>' +
                                '<td>' + value.created_at + '</td>' +
                                '<td>' + value.updated_at + '</td>' +
                                '<td style="text-align: center;">' + showUsedBadge + '</td>' +
                                '<td style="text-align: center;">' + value.sort + '</td>' + <!-- 新增排序列 -->
                                '<td style="text-align: center;">' +
                                '<div class="btn-group">' +
                                '    <a class="btn btn-xs btn-default btn-sync" href="#!" title=""' +
                                '                                           data-id="' + value.id + '"' +
                                '                                           data-title="' + value.title + '"' +
                                '                                           data-toggle="tooltip" data-original-title="一键同步">一键同步</a>' +
                                '    <a class="btn btn-xs btn-default btn-detail" href="#!" title=""' +
                                '                                           data-title="' + value.title + '"' +
                                '                                           data-description="' + value.description + '"' +
                                '                                           data-toggle="tooltip" data-original-title="详情">详情</a>' +
                                '    <a class="btn btn-xs btn-default btn-option" href="#!" title=""' +
                                '                                           data-id="' + value.id + '"' +
                                '                                           data-is-used="' + value.is_used + '"' +
                                '                                           data-toggle="tooltip" data-original-title="' + optionUsedName + '">' + optionUsedName + '</a>' +
                                '    <a class="btn btn-xs btn-default btn-confirm" href="#!" title=""' +
                                '                                           data-id="' + value.id + '"' +
                                '                                           data-toggle="tooltip" data-original-title="删除">删除</a>' +
                                '    <a class="btn btn-xs btn-default btn-update" href="#!" title=""' +
                                '                                           data-id="' + value.id + '"' +
                                '                                           data-thumb="' + value.thumb + '"' +
                                '                                           data-url="' + value.url + '"' +
                                '                                           data-category="' + value.category + '"' +
                                '                                           data-title="' + value.title + '"' +
                                '                                           data-description="' + value.description + '"' +
                                '                                           data-category_id="' + value.category_id + '"' +
                                '                                           data-sort_order="' + value.sort + '"' + <!-- 新增排序数据 -->
                                '                                           data-toggle="tooltip" data-original-title="编辑">编辑</a>' +
                                '</div>' +
                                '</td>' +
                                '</tr>';
                            $(".tbody").append(tr);
                        });
                    } else {
                        // 数据为空
                        $(".tbody").html("");
                        $(".tbody").append('<tr><td colspan="7" style="text-align: center">暂无数据</td></tr>');
                    }
                },
                function (response) {
                    AjaxError(response);
                }
            );
        }

        // 一键同步
        $(document).on('click', '.btn-sync', function () {
            const id = $(this).attr('data-id');
            const business_title = $(this).attr('data-title');
            $.confirm({
                title: '谨慎操作',
                content: '确认要 <strong style="color: red">一键同步 </strong>：' + business_title + ' 吗？',
                icon: 'mdi mdi-alert',
                animation: 'scale',
                closeAnimation: 'zoom',
                buttons: {
                    okay: {
                        text: '确认',
                        keys: ['enter'],
                        btnClass: 'btn-orange',
                        action: function () {
                            AjaxForm(
                                "GET",
                                '/api/admin/site/sync/' + id,
                                "",
                                function () {
                                },
                                function (data) {
                                    $.alert({
                                        title: '操作成功',
                                        icon: 'mdi mdi-check-decagram',
                                        type: 'green',
                                        content: '编号：' + data.id + ' 已同步。',
                                        buttons: {
                                            okay: {
                                                text: '关闭',
                                                action: function () {
                                                    const currentPage = document.querySelector('.page-link.pageActive').textContent;
                                                    getPageListData(parseInt(currentPage), 10, document.getElementById('search-keyword').value, $("#category-filter").val());
                                                }
                                            }
                                        }
                                    });
                                },
                                function (response) {
                                    AjaxError(response);
                                }
                            );
                        }
                    },
                    cancel: {
                        text: '取消',
                        keys: ['ctrl', 'shift'],
                    }
                }
            });
        });
        // 详情
        $(document).on('click', '.btn-detail', function () {
            const business_title = $(this).attr('data-title');
            const business_description = $(this).attr('data-description');
            $.alert({
                title: '详情',
                content: '名称简介 ：' + business_title + '<br/>描述：' + business_description,
                type: 'green',
                animation: 'scale',
                draggable: true,
            });
        });
        // 启用/禁用
        $(document).on('click', '.btn-option', function () {
            const id = $(this).attr('data-id');
            const isUsed = $(this).attr('data-is-used');
            var tipMessage = "";
            var wantUsed = false;
            if (isUsed === "true") { // true=当前为启用状态，需要改成禁用
                tipMessage = "禁用";
                wantUsed = false;
            }
            if (isUsed === "false") {
                tipMessage = "启用";
                wantUsed = true;
            }
            const patchData = {
                id: id,
                is_used: wantUsed,
            };
            $.confirm({
                title: '谨慎操作',
                content: '确认要 <strong style="color: red">' + tipMessage + '</strong> 吗？',
                icon: 'mdi mdi-alert',
                animation: 'scale',
                closeAnimation: 'zoom',
                buttons: {
                    okay: {
                        text: '确认',
                        keys: ['enter'],
                        btnClass: 'btn-orange',
                        action: function () {
                            AjaxForm(
                                "PUT",
                                "/api/admin/site/" + id,
                                patchData,
                                function () {
                                },
                                function (data) {
                                    $.alert({
                                        title: '操作成功',
                                        icon: 'mdi mdi-check-decagram',
                                        type: 'green',
                                        content: '编号：' + data.id + ' 已' + tipMessage + '。',
                                        buttons: {
                                            okay: {
                                                text: '关闭',
                                                action: function () {
                                                    const currentPage = document.querySelector('.page-link.pageActive').textContent;
                                                    getPageListData(parseInt(currentPage), 10, document.getElementById('search-keyword').value, $("#category-filter").val());
                                                }
                                            }
                                        }
                                    });
                                },
                                function (response) {
                                    AjaxError(response);
                                }
                            );
                        }
                    },
                    cancel: {
                        text: '取消',
                        keys: ['ctrl', 'shift'],
                    }
                }
            });
        });
        // 删除
        $(document).on('click', '.btn-confirm', function () {
            const id = $(this).attr('data-id');
            $.confirm({
                title: '谨慎操作',
                content: '确认要 <strong style="color: red">删除</strong> 吗？',
                icon: 'mdi mdi-alert',
                animation: 'scale',
                closeAnimation: 'zoom',
                buttons: {
                    okay: {
                        text: '确认',
                        keys: ['enter'],
                        btnClass: 'btn-orange',
                        action: function () {
                            AjaxForm(
                                "DELETE",
                                '/api/admin/site/' + id,
                                "",
                                function () {
                                },
                                function (data) {
                                    $.alert({
                                        title: '操作成功',
                                        icon: 'mdi mdi-check-decagram',
                                        type: 'green',
                                        content: '编号：' + data.id + ' 已删除。',
                                        buttons: {
                                            okay: {
                                                text: '关闭',
                                                action: function () {
                                                    const currentPage = document.querySelector('.page-link.pageActive').textContent;
                                                    getPageListData(parseInt(currentPage), 10, document.getElementById('search-keyword').value, $("#category-filter").val());
                                                }
                                            }
                                        }
                                    });
                                },
                                function (response) {
                                    AjaxError(response);
                                }
                            );
                        }
                    },
                    cancel: {
                        text: '取消',
                        keys: ['ctrl', 'shift'],
                    }
                }
            });
        });
        // 编辑
        $(document).on('click', '.btn-update', function () {
            const id = $(this).attr('data-id');
            const thumb = $(this).attr('data-thumb');
            const title = $(this).attr('data-title');
            const url = $(this).attr('data-url');
            const description = $(this).attr('data-description');
            const category_id = $(this).attr('data-category_id');
            const sort = $(this).attr('data-sort_order'); // 获取排序数据

            $.confirm({
                title: '编辑网站',
                //content: 'url:form.html',  // 也可以采用url形式
                content: '<div class="form-group p-1 mb-0">' +
                    '<div class="input-group mb-3">' +
                    '<div class="input-group-prepend">' +
                    '<span class="input-group-text">分类</span>' +
                    '</div>' +
                    '<select class="form-control selectpicker col-lg-5" id="category_id" data-width="auto" data-live-search="true" data-size="5"></select>' +
                    '</div>' +
                    '<div>' +
                    '<input  style="display:none"  autofocus="" class="form-control" type="text"  maxLength="200" id="id" value="' + id + '">' +
                    '</div>' +
                    '<div>' +
                    '<label class="control-label">Logo</label>' +
                    '<input  autofocus="" class="form-control" type="text"  maxLength="200" id="thumb" placeholder="请输入Logo链接" value="">' +
                    '</div>' +
                    '<input id="file" name="file" type="file" class="file">' +
                    '<div>' +
                    '  <label class="control-label">名称</label>' +
                    '  <input autofocus="" type="text"  placeholder="请输入网站名称" class="form-control"  id="title" value="' + title + '">' +
                    '</div>' +
                    '<div>' +
                    '  <label class="control-label">链接</label>' +
                    '  <input autofocus="" type="text"  placeholder="请输入网站地址" class="form-control"  id="url" value="' + url + '">' +
                    '</div>' +
                    '<div>' +
                    '  <label class="control-label">网站描述</label>' +
                    '  <textarea class="form-control" maxlength="225" rows="2" id="description" placeholder="网站描述"  id="title">' + description + '</textarea>' +
                    '</div>' +
                    '<div>' +
                    '  <label>排序</label>' +
                    '  <small class="help-block">(相同分类下网站排序)</small>' +
                    '  <input autofocus="" type="number"  placeholder="请输入排序值" class="form-control"  id="sort_order" value="' + sort + '">' + <!-- 新增排序输入框 -->
                    '</div>',
                onOpen: function () {
                    // bootstrap-fileinput 初始化引导文件输入插件
                    $('#file').fileinput({
                        language: 'zh',
                        showPreview: false,  // 显示预览
                        maxFileSize: 2500,  // 最大文件大小
                        initialPreviewAsData: true,
                        initialPreview: [],  // 初始预览数据
                        allowedFileExtensions: ["jpg", "png"],  // 允许的文件扩展名
                        browseLabel: '选择文件', // 自定义浏览按钮标签
                        removeLabel: '删除', // 自定义删除按钮标签
                        showUpload: false // 隐藏上传按钮
                    });
                    AjaxFormNoAsync(
                        "GET",
                        "/api/admin/category",
                        "",
                        function () {
                        },
                        function (data) {
                            const treeData = buildTree(data.list);// 将扁平化数据转换为树形结构
                            const selectElement = document.getElementById('category_id');// 获取 <select> 元素
                            renderTreeToSelect(treeData, selectElement, 0, [parseInt(category_id)]);  // 渲染树形结构到 <select>
                            $("#category_id").selectpicker('refresh');// 初始化 Bootstrap Select
                        },
                        function (response) {
                            AjaxError(response);
                        }
                    );
                },
                buttons: {
                    sayMyName: {
                        text: '确认',
                        btnClass: 'btn-orange',
                        action: function () {
                            const thumb = $("#thumb").val();
                            const title = $("#title").val();
                            if (title === "") {
                                $.alert({
                                    title: '温馨提示',
                                    icon: 'mdi mdi-alert',
                                    type: 'orange',
                                    content: '请输入网站名称。',
                                });
                                return false;
                            }
                            const url = $("#url").val();
                            if (url === "") {
                                $.alert({
                                    title: '温馨提示',
                                    icon: 'mdi mdi-alert',
                                    type: 'orange',
                                    content: '请输入网站链接。',
                                });
                                return false;
                            }
                            const description = $("#description").val();
                            if (description === "") {
                                $.alert({
                                    title: '温馨提示',
                                    icon: 'mdi mdi-alert',
                                    type: 'orange',
                                    content: '请输入网站描述。',
                                });
                                return false;
                            }
                            const formData = new FormData();
                            formData.append('id', id);
                            formData.append('thumb', thumb);
                            formData.append('title', title);
                            formData.append('url', url);
                            formData.append('description', description);
                            formData.append('file', $("#file")[0].files[0]);
                            formData.append('category_id', $("#category_id").val());
                            formData.append('sort', $("#sort_order").val()); // 添加排序值

                            AjaxMultipartForm(
                                "PUT",
                                "/api/admin/site/" + id,
                                formData,
                                function () {
                                },
                                function (data) {
                                    $.alert({
                                        title: '操作成功',
                                        icon: 'mdi mdi-check-decagram',
                                        type: 'green',
                                        content: '编号：' + data.id + ' 修改完成。',
                                        buttons: {
                                            okay: {
                                                text: '关闭',
                                                action: function () {
                                                    const currentPage = $(".page-link.pageActive").text(); // 获取当前页码
                                                    getPageListData(currentPage, 10, $("#search-keyword").val(), $("#category-filter").val()); // 重新加载当前页数据
                                                }
                                            }
                                        }
                                    });
                                },
                                function (response) {
                                    AjaxError(response);
                                }
                            );
                        }
                    },
                    '取消': function () {
                    }
                }
            });
        });
        // 搜索
        $(document).on('click', '.btn-search', function () {
            getPageListData(0, 0, $("#search-keyword").val(), $("#category-filter").val())
        })
    })
</script>
<script>
    $(document).ready(function () {
        $(document).on('click', '#exportBtn', function () {
            const searchKeyword = $("#search-keyword").val();
            exportData(searchKeyword);            // 发起导出请求
        });

        function exportData(searchKeyword) {
            let url = "/api/admin/site/export";
            if (searchKeyword) {
                url += "?search=" + encodeURIComponent(searchKeyword);
            }
            // 发起 GET 请求
            $.ajax({
                url: url,
                method: "GET",
                xhrFields: {
                    responseType: 'blob' // 重要：告诉 jQuery 返回的是一个二进制文件
                },
                success: function (data, status, xhr) {
                    const contentDisposition = xhr.getResponseHeader('Content-Disposition');// 获取文件名（从响应头中提取）
                    let fileName = "sites.xlsx"; // 默认文件名
                    if (contentDisposition && contentDisposition.includes('filename=')) {
                        fileName = contentDisposition.split('filename=')[1].trim();
                    }
                    const link = document.createElement('a');
                    link.href = window.URL.createObjectURL(data); // 将文件流转换为 URL
                    link.download = fileName; // 设置下载文件名
                    document.body.appendChild(link);
                    link.click(); // 触发下载
                    document.body.removeChild(link); // 移除链接元素
                },
                error: function (xhr, status, error) {
                    $.alert({
                        title: '导出失败',
                        icon: 'mdi mdi-alert',
                        type: 'red',
                        content: '导出文件时发生错误：' + error,
                    });
                }
            });
        }
    });
</script>
</body>
</html>
